from django.shortcuts import render, HttpResponse
from utrl.centent import sms
# Create your views here.
from django import forms
from django.core.validators import RegexValidator
import re
import random
import redis

conn = redis.Redis(host='192.168.0.141', password=8852348, port=6379,
                       encoding='utf-8')



def register(request):
    sms.send_sms_single('13027088268', '602718', [2222 ])
    #return HttpResponse('发送成功')


class RegisTerS(forms.Form):



    name = forms.CharField(label='用户名', max_length=32, widget=forms.TextInput(attrs={'class':'form-control'}))
    age = forms.CharField(label='密码', widget=forms.PasswordInput(attrs={'class':'form-control'}))

    mobile_phone = forms.CharField(label='手机号', validators=[
        RegexValidator(r'^(1[3|4|5|7|9|8])\d{9}$', '手机格式不正确')],widget=forms.TextInput(attrs={'class':'form-control'}) )
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'class':'form-control', 'style': 'width:200px'}))






def register1(request):
    fors = RegisTerS()

    return render(request, 'registers.html', {'fors': fors})



def send_sms(request):
    # 短信的ajax信息的请求
    tpl = request.POST.get('tpl')  # 发送过来的id码
    phone = request.POST.get('phone')  # 发送过来的手机号

    ret = re.match(r'^(1[3|4|5|7|9|8])\d{9}$', str(phone))
    if ret == None:
        return HttpResponse('输入的手机号不正确')
    code = random.randrange(1000,9999)
    sms.send_sms_single(str(phone), str(tpl), [code,])  # 调用发短信函数

    conn.set(str(phone), code, ex=60)  # redis里写入一条数据 60秒后失效
    # value = conn.get('13027088268')
    # print(value.decode('utf-8'))
    return HttpResponse('短信已经发送至您的手机')

def register_information(request):
    name = request.POST.get('name')
    password = request.POST.get('password')
    phone = request.POST.get('phone')
    code = request.POST.get('code')

    print('用户名', name, '密码', password, '手机号', phone, '验证码', code)

    return HttpResponse('ok')










